package com.sgb.kjwl.view.widget.transport;

import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;

import androidx.core.util.Pair;

import com.bumptech.glide.Glide;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.databinding.AppOfferDetailOwnerPopLayoutBinding;
import com.sgb.kjwl.model.entity.self.OrderQuoteEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.LonLatUtils;
import com.sgb.kjwl.utils.NumberUtil;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.UserOperating;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.ui.activity.transport.owner.TransportOrderDetailOwnerActivity;
import com.sgb.net.util.RequestUtil;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.PopViewHolder;
import com.swgk.core.dialog.RoundDialog;
import com.im.immodel.IMUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.StringUtil;

import org.greenrobot.eventbus.EventBus;

import retrofit2.Call;

/**
 * Describe:    报价详情弹窗——货主视角（普通货源）
 * Author:  yangLei
 * Date:    2021/9/18
 */
public class OfferDetailOwnerPopWindow extends BasePopWindow implements View.OnClickListener {
    private OrderQuoteEntity offerEntity;
    private AppOfferDetailOwnerPopLayoutBinding mBinding;

    //报价状态刷新回调
    private CallBack mCallBack;

    public interface CallBack {
        void refreshOfferStatus(OrderQuoteEntity entity);
    }

    public OrderQuoteEntity getOfferEntity() {
        return offerEntity;
    }

    public void setOfferEntity(OrderQuoteEntity offerEntity) {
        setData(offerEntity);
    }

    public OfferDetailOwnerPopWindow(Context context, CallBack callBack) {
        super(context, DIR_DOWN_UP);
        this.mCallBack = callBack;
    }

    @Override
    protected int popLayout() {
        return R.layout.app_offer_detail_owner_pop_layout;
    }

    @Override
    protected void initView(PopViewHolder holder) {
        mBinding = (AppOfferDetailOwnerPopLayoutBinding) holder.getmBinding();
        mBinding.setOnClick(this::onClick);
    }

    /**
     * 加载报价详情
     */
    public void setData(OrderQuoteEntity entity) {
        this.offerEntity = entity;
        if (offerEntity == null) return;
        //头像
        if (!TextUtils.isEmpty(entity.getLogo())) {
            Glide.with(mContext).load(entity.getLogo())
                    .placeholder(R.drawable.icon_default_profile_photo_round)
                    .into(mBinding.offerUserIcon);
        }
        //预计到场时间
        if (entity.getInTime() != null && entity.getInTime() > 0) {
            mBinding.predictArriveTime.setText(DateUtils.timestampTo13DateNos(entity.getInTime()));
        } else {
            mBinding.predictArriveTime.setText("/");
        }
        //运费报价(单价)
        mBinding.offerPriceUnit.setText(!TextUtils.isEmpty(entity.getFreight()) ? NumberUtil.trim0(entity.getFreight()) + entity.getQuotationFreightUnit() : "/");
        //运费报价(总价)
        mBinding.offerPrice.setText(!TextUtils.isEmpty(entity.getAllFreight()) ? NumberUtil.trim0(entity.getAllFreight()) + "元" : "/");
        //距离装货地
        double distance = 0.0d;
        if (!TextUtils.isEmpty(entity.getDistance())) {
            distance = Double.parseDouble(entity.getDistance());
        } else if (entity.getLongitude() != null && entity.getLongitude() > 0
                && entity.getLatitude() != null && entity.getLatitude() > 0) {
            distance = LonLatUtils.getDistance(entity.getLongitude(), entity.getLatitude(),
                    NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "")),
                    NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, ""))
            );
        }
        if (distance <= 0) {
            mBinding.offerDistance.setText("/");
        } else {
            mBinding.offerDistance.setText(distance < 1 ? "1km以内" : StringUtil.formatUpDistance(String.valueOf(distance)) + "km");
        }

        //位置
        mBinding.offerAddress.setText(!TextUtils.isEmpty(entity.getCompanyTeamAddress()) ? entity.getCompanyTeamAddress() : "/");
        //报价方名字
        String title = "";
        if (!TextUtils.isEmpty(entity.getOfferType())) {
            if (entity.getOfferType().equals("1")) {
                title = !TextUtils.isEmpty(entity.getCompanyName()) ? entity.getCompanyName() : "";
            } else if (entity.getOfferType().equals("2")) {
                title = !TextUtils.isEmpty(entity.getTeamName()) ? entity.getTeamName() : "";
            } else if (entity.getOfferType().equals("3")) {
                title = !TextUtils.isEmpty(entity.getName()) ? entity.getName() : "";
            }
        }
        mBinding.offerUserName.setText(title);

        //车辆信息
        boolean isShowCarInfo = false;
        //承运车辆展示逻辑修改，企业和团队可展示多辆，没有不展示
        if (entity.getDriverAuths() != null && entity.getDriverAuths().size() > 0) {
            if (!TextUtils.isEmpty(entity.getOfferType())) {
                if (entity.getOfferType().equals("1") || entity.getOfferType().equals("2")) {//团队/企业
                    int carNum = 0;
                    String carInfo = "";
                    for (int i = 0; i < entity.getDriverAuths().size(); i++) {
                        if (entity.getDriverAuths().get(i) != null && !TextUtils.isEmpty(entity.getDriverAuths().get(i).getCarNumber())) {
                            carNum++;
                            if (carNum == 1) {
                                carInfo += entity.getDriverAuths().get(i).getCarNumber() + "  ";
                            } else if (carNum == 2) {
                                carInfo += entity.getDriverAuths().get(i).getCarNumber();
                            } else if (carNum > 2) {
                                carInfo += "...";
                                break;
                            }
                        }
                    }
                    if (!TextUtils.isEmpty(carInfo)) {
                        mBinding.offerCarInfo.setText(carInfo);
                        isShowCarInfo = true;
                    }
                } else if (entity.getOfferType().equals("3")) {//个人
                    OrderQuoteEntity.DriverAuth car = entity.getDriverAuths().get(0);
                    if (car != null) {
                        String carNum;
                        carNum = !TextUtils.isEmpty(car.getCarNumber()) ? car.getCarNumber() : "";

                        StringBuilder carInfo = new StringBuilder();
                        carInfo.append(carNum + "(");
                        if (!TextUtils.isEmpty(car.getCarTypeName())) {
                            carInfo.append(car.getCarTypeName());
                        }
                        if (!TextUtils.isEmpty(car.getCarLenName())) {
                            carInfo.append("/车长" + car.getCarLenName());
                        }
                        if (!TextUtils.isEmpty(car.getHeightHurdle())) {
                            carInfo.append("/栏高" + NumberUtil.trim0(car.getHeightHurdle()) + "米");
                        }
                        if (!TextUtils.isEmpty(car.getIsDumper())) {
                            carInfo.append("/" + car.getIsDumper());
                        }
                        carInfo.append(")");
                        mBinding.offerCarInfo.setText(carInfo.toString());
                        isShowCarInfo = true;
                    }
                }
            }
        }
        mBinding.offerCarInfoLayout.setVisibility(isShowCarInfo ? View.VISIBLE : View.GONE);

        mBinding.contacts.setText(!TextUtils.isEmpty(entity.getContacts()) ? entity.getContacts() : "/");

        mBinding.disabledCauseLayout.setVisibility(View.GONE);
        mBinding.messagePriceHint.setVisibility(View.GONE);
        mBinding.messagePriceAmount.setVisibility(View.GONE);
        mBinding.rightBtn.setVisibility(View.GONE);
        if (entity.getFailureCause() != null) {
            String failueCause = "";
            switch (entity.getFailureCause()) {
                case 0:
                    failueCause = "车主超时未支付信息费";
                    break;
                case 1:
                    failueCause = "货主未同意报价";
                    break;
                case 2:
                    failueCause = "货主已下架货源";
                    break;
                case 3:
                    failueCause = "货主已删除货源";
                    break;
            }
            mBinding.offerStatues.setText("报价已失效");
            mBinding.offerStatues.setTextColor(Color.parseColor("#C0C4CC"));
            mBinding.disabledCause.setText(failueCause);
            mBinding.disabledCauseLayout.setVisibility(View.VISIBLE);
        } else
            //报价状态
            if (!TextUtils.isEmpty(entity.getOfferStatus())) {
                //1已报价  2待支付(已同意)  3已支付 4超时未支付 5已失效/货主未同
                switch (entity.getOfferStatus()) {
                    case "1":
                        mBinding.offerStatues.setText("已报价");
                        mBinding.offerStatues.setTextColor(Color.parseColor("#5792FD"));
                        mBinding.rightBtn.setText("下单");
                        mBinding.rightBtn.setVisibility(View.VISIBLE);
                        break;

                    case "2":
                        mBinding.offerStatues.setText("报价待支付");
                        mBinding.offerStatues.setTextColor(Color.parseColor("#FFC000"));
                        mBinding.messagePriceHint.setVisibility(View.VISIBLE);
                        mBinding.messagePriceAmount.setVisibility(View.VISIBLE);
                        if (!TextUtils.isEmpty(entity.getSourceMessagePrice())) {
                            mBinding.messagePriceAmount.setText(NumberUtil.trim0(entity.getSourceMessagePrice()) + "元");
                        }
                        break;

                    case "3":
                        mBinding.offerStatues.setText("报价已支付");
                        mBinding.offerStatues.setTextColor(Color.parseColor("#06C764"));
                        mBinding.rightBtn.setText("查看订单");
                        mBinding.rightBtn.setVisibility(View.VISIBLE);
                        break;
                }
            }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_btn:
                dissMiss();
                break;

            case R.id.exchange_tab:
                imClick();
                break;

            case R.id.call_phone_tab:
                telClick();
                break;

            case R.id.right_btn:
                if (!TextUtils.isEmpty(offerEntity.getOfferStatus())) {
                    if (offerEntity.getOfferStatus().equals("1")) {
                        showOfferDialog(offerEntity);
                    } else if (offerEntity.getOfferStatus().equals("3") && !TextUtils.isEmpty(offerEntity.getOrderNo())) {
                        ActivityJump.jumpToActivity(mContext, TransportOrderDetailOwnerActivity.class, Pair.create("no", offerEntity.getOrderNo()),
                                Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.GOODS_OWNER));
                    }
                }
                break;
        }
    }

    /**
     * 展示同意报价对话框
     */
    private void showOfferDialog(OrderQuoteEntity entity) {
        String content;
        if (!TextUtils.isEmpty(entity.getSourceMessagePrice()) && !NumberUtil.trim0(entity.getSourceMessagePrice()).equals("0")) {//有信息费
            content = "下单后，承运人支付信息费后生成货运订单，您确定要下单吗？";
        } else {//无信息费
            content = "下单后，将生成货运订单，您确定要下单吗？";
        }
        new RoundDialog.Builder(mContext)
                .title("提示")
                .content(content)
                .cancel("取消")
                .confirm("确定")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .confirmCallback(v -> {
                    agreeOffer();
                })
                .show();
    }

    /**
     * 同意车主接单/报价
     */
    public void agreeOffer() {
        RequestUtil requestUtil = RequestUtil.map();
        requestUtil.add("no", offerEntity.getGoodsOfferNo());
        requestUtil.add("goodsSourceNo", offerEntity.getSourceNo());
        DialogHelper.showProgressDialog(mContext, "数据加载中...");
        NewAPIManager.getInstance().getLogisticsAPI().agreeGeneralOffer(requestUtil.buildMap())
                .enqueue(new ICallBack<BaseEntity>() {
                    @Override
                    public void onSuccess(BaseEntity data) {
                        //操作成功，刷新窗口，刷新外部数据
                        String no = (String) data.getData();
                        if (!TextUtils.isEmpty(no)) {
                            offerEntity.setOrderNo(no);
                        }
                        offerEntity.setOfferStatus("2");
                        setData(offerEntity);
                        if (mCallBack != null) {//同意报价成功
                            mCallBack.refreshOfferStatus(offerEntity);
                        }
                        //更新货源管理列表数据
                        EventBus.getDefault().post(LogisticsEvent.make(EventConstant.EVENT_GOODS_AGREED_OFFER, null));
                    }

                    @Override
                    public void onFailure(Call<BaseEntity> call, Throwable t) {
                    }

                    @Override
                    public void onFailureWithEntity(BaseEntity entity) {
                        if (APIManager.CAR_ABNORMAL.equals(entity.getCode())) {
                            showCarTipDialog(entity.getMsg());
                        } else if ("231".equals(entity.getCode())//已超出处理时间
                                || "230".equals(entity.getCode())) {//货源状态非待接单
                            MToast.showToast(mContext, DefaultUtil.getString(entity.getMsg()));
                            if (mCallBack != null) {//同意报价状态异常
                                mCallBack.refreshOfferStatus(offerEntity);
                            }
                            if (isShowing()) {
                                dismiss();
                            }
                        } else {
                            MToast.showToast(mContext, DefaultUtil.getString(entity.getMsg()));
                        }
                    }
                });
    }

    /**
     * 车辆异常提示弹窗
     */
    private void showCarTipDialog(String content) {
        new RoundDialog.Builder(mContext)
                .title("当前该车状态异常，无法进行操作，可联系车主处理")
                .content(DefaultUtil.getString(content))
                .confirm("确定")
                .singleBtn(true)
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .show();
    }

    /**
     * 对字符加星号处理：除前面几位和后面几位外，其他的字符以星号代替
     *
     * @param content  传入的字符串
     * @param frontNum 保留前面字符的位数
     * @param endNum   保留后面字符的位数
     * @return 带星号的字符串
     */
    public static String replaceString2Star(String content, int frontNum, int endNum) {
        if (content == null || content.trim().isEmpty())
            return "";
        int len = content.length();

        if (frontNum >= len || frontNum < 0 || endNum >= len || endNum < 0)
            return content;

        if (frontNum + endNum >= len)
            return content;

        int beginIndex = frontNum;
        int endIndex = len - endNum;
        char[] cardChar = content.toCharArray();

        for (int j = beginIndex; j < endIndex; j++) {
            cardChar[j] = '*';
        }

        return new String(cardChar);
    }

    private void imClick() {
        //检查登录状态
        if (UserOperating.getInstance().isNotLogged(mContext)) {
            return;
        }
        if (offerEntity != null && !TextUtils.isEmpty(offerEntity.getImAccount())) {
            IMUtils.getInstance().buildSingleTalking(offerEntity.getImAccount());
        }
    }

    private void telClick() {
        //检查登录状态
        if (UserOperating.getInstance().isNotLogged(mContext)) {
            return;
        }
        if (offerEntity != null && !TextUtils.isEmpty(offerEntity.getContactsNumber())) {
            new RoundDialog.Builder(mContext)
                    .title("是否拨打电话")
                    .content(offerEntity.getContactsNumber())
                    .confirm("拨打")
                    .cancelable(false)
                    .confirmCallback(v -> ActivityJump.jumpToPhone(mContext, offerEntity.getContactsNumber()))
                    .show();
        }
    }
}
